import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
const service = axios.create({
    //基础地址
    baseURL: 'https://api-hmzs.itheima.net/v1',
    timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        //此处发送token给api
        const token = store.state.user.token
        if (token) {
            config.headers.Authorization = token
        }

        return config //携带请求数据：包括请求头：token cookie
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        return response.data //服务器返回数据
    },
    error => {
        // console.dir(error)
        //在此处处理错误
        //处理token失效
        if (error.response.status === 401) {
            //当token失效时，让它跳回登录页面
            store.commit('user/removeToken')
            router.push('/login')
        }
        Message.error(error.response.data.msg)
        return Promise.reject(error)
    }
)

export default service